<script lang="ts">
import Vue from 'vue'
import NavBar from "@/components/nav-bar/nav-bar.vue";
import uploadSelectPopup from "@/components/upload-select-popup/upload-select-popup.vue";
import {editImageChange} from "@/utils/utils";
import tips from "@/utils/tips";
import {uploadImageServer} from "@/services/office";

interface IdItem {
  name: string;
  isShow: boolean;
  icon: string;
  file: string;
  ml?: string;
  mr?: string;
}

export default Vue.extend({
  name: "multi_printer_id",
  components: {uploadSelectPopup, NavBar},
  data() {
    return {
      idList: [
        {name: 'id_front', isShow: true, file: '', icon: '/static/print_id/id.png', ml: "25%", mr: "25%"},
        {name: 'id_after', isShow: true, file: '', icon: '/static/print_id/id_sel.png', ml: "25%", mr: "25%"},
        {name: 'id_front', isShow: false, file: '', icon: '/static/print_id/id.png', ml: "25%", mr: "25%"},
        {name: 'id_after', isShow: false, file: '', icon: '/static/print_id/id_sel.png'},
        {name: 'id_front', isShow: false, file: '', icon: '/static/print_id/id.png'},
        {name: 'id_after', isShow: false, file: '', icon: '/static/print_id/id_sel.png'},
        {name: 'id_front', isShow: false, file: '', icon: '/static/print_id/id.png'},
        {name: 'id_after', isShow: false, file: '', icon: '/static/print_id/id_sel.png'},
        {name: 'all', isShow: false, file: '', icon: '', ml: "", mr: ""},
      ] as IdItem[],

      showUploadPopup: false, // 上传图片弹窗
      clickType: 0, // 当前 current
    }
  },
  computed: {
    lang() {
      return this.$t('multi_print_id')
    }
  },
  methods: {
    // 选择打印什么的
    onSelectedRadio(event: any) {
      const {value} = event.detail
      const {idList} = this
      const clickAll = idList[8].isShow;

      let selectedSum = 0;
      // 全部改变未选定的
      for (let i = 0; i < idList.length; i++) {
        this.idList[i].isShow = false
      }

      // 选定的改变选定的
      for (let i = 0; i < value.length; i++) {
        this.idList[value[i]].isShow = true
        selectedSum++;
      }

      // 如果点的全选
      if (!clickAll && idList[8].isShow) {
        for (let i = 0; i < idList.length; i++) {
          this.idList[i].isShow = true
        }
        selectedSum = idList.length;
      } else {
        if (value.length === 8 && idList[8].isShow) {
          this.idList[8].isShow = false;
        }
      }
      // 纸下面保持距离去掉
      if (idList[8].isShow || idList[7].isShow) {
        this.paddingBottom = "40rpx"
      } else {
        this.paddingBottom = "160rpx"
      }

      //根据数量设置间隔
      for (let i = 0; i < idList.length; i++) {
        if (selectedSum <= 3) {
          this.idList[i].ml = "25%";
          this.idList[i].mr = "25%";
        } else {
          this.idList[i].ml = "0%";
          this.idList[i].mr = "0%";
        }
      }
    },
    // 上传照片选择的
    showUploadImage(type: number) {
      this.clickType = type;
      this.showUploadPopup = true;
    },
    // 微信选取图片
    chooseMessage() {
      const that = this;
      uni.chooseMessageFile({
        count: 1,
        type: 'image',
        success(res) {
          that.processImage(res.tempFiles[0].path);
        }
      });
    },
    // 本地图片上传或拍照
    chooseImage(index: string) {
      const that = this;
      const sourceTypes = ['camera', 'album'];
      uni.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: [sourceTypes[index]],
        sizeType: ['original', 'compressed'],
        success: function (res) {
          that.processImage(res.tempFiles[0].tempFilePath);
        }
      });
    },

    // 处理图片编译
    async processImage(src: string) {
      try {
        this.idList[this.clickType].file = await editImageChange(src);
      } catch (error) {
        console.error('图片处理失败:', error);
      }
    },

    // 删除照片
    closeId(type: number) {
      this.idList[type].file = ''
    },

    // 编译照片
    onEditImage(type: number) {
      this.clickType = type;
      const url = this.idList[type].file;
      this.processImage(url)
    },

    // 绘制带圆角的矩形
    drawRoundedRect(ctx: any, x: number, y: number, width: number, height: number, radius: number) {
      ctx.beginPath();
      ctx.moveTo(x + radius, y);
      ctx.lineTo(x + width - radius, y);
      ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
      ctx.lineTo(x + width, y + height - radius);
      ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
      ctx.lineTo(x + radius, y + height);
      ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
      ctx.lineTo(x, y + radius);
      ctx.quadraticCurveTo(x, y, x + radius, y);
      ctx.closePath();
      ctx.clip(); // 设置剪切区域为当前路径
    },

    // 合并照片
    drawAndShareImage() {
      // 绘制背景海报到canvas
      const idWidth = 684;      // 身份证宽度
      const idHeight = 432;     // 身份证高度
      const a4Width = 1588;         // A4纸宽度
      const a4Height = 2246;        // A4纸高度
      // 检查是否有选项
      const {idList} = this
      let checkSum = 0;

      for (let i = 0; i < idList.length - 1; i++) {
        if (idList[i].isShow) {
          checkSum++;
        }
      }
      // 最少一个
      if (checkSum <= 0) {
        tips.toast(this.lang.selected_one)
        return;
      }

      // 检查图片数是否一致
      let fullNums = 0;
      for (let i = 0; i < idList.length; i++) {
        if (idList[i].file !== '') {
          fullNums++;
        }
      }
      if (fullNums !== checkSum) {
        tips.toast(this.lang.selected_image_upload_all)
        return;
      }

      const that = this;
      // this.showUploadPopup = true;
      uni.showLoading({title: '加载中....', mask: true})

      const context = uni.createCanvasContext('multiIdCanvas', this);
      context.fillStyle = "#FFFFFF";
      const one = 1
      context.fillRect(0, 0, a4Width * one, a4Height * one); // 绘制背景矩形
      // <= 3 ，居中，
      let ml = 80;
      let my = 0;
      let draw = 0;

      if (checkSum <= 3) {
        ml = 454; // 3个及以下时居中
        my = (a4Height - 510 * checkSum) / 2 - 80;
      } else {
        // 根据数量调整位置
        if (checkSum === 4) { // 4张
          // my = (2246 - 510 * 2) / 2 - 80;
          my = (a4Height - 510 * 2) / 2 - 600;
        } else if (checkSum === 5 || checkSum === 6) { // 5张或6张
          // my = (2246 - 510 * 3) / 2 - 80;
          my = (a4Height - 510 * 3) / 2 - 360;
        } else if (checkSum === 7 || checkSum === 8) { // 7张或8张
          my = (a4Height - 510 * 4) / 2 - 120;
        }
      }

      // 绘制每个身份证图片
      for (let i = 0; i < idList.length; i++) {
        if (idList[i].isShow && idList[i].file !== '') {
          context.drawImage(idList[i].file, ml * one, (80 + my) * one, idWidth, idHeight);
          draw++;
          // 根据指定的ml调整位置
          if (idList[i].ml === "25%") {
            my += 510; // 调整垂直位置
            ml = 454;  // 重置水平位置
          } else {
            if (draw % 2 === 1) { // 处理奇数项
              // ml = 796; // 一排两个距离
              ml = 830; // 一排两个距离
            } else {
              ml = 80; // 左边距离
              my += 510; // 往下距离
            }
          }
        }
      }

      context.draw()
      setTimeout(() => {
        uni.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: a4Width * one,
          height: a4Height * one,
          destWidth: a4Width * one,
          destHeight: a4Height * one,
          canvasId: 'multiIdCanvas',
          success: (res) => {
            console.log(res.tempFilePath)

            // 上传图片到服务器
            uni.uploadFile({
              url: uploadImageServer,
              name: 'file',
              filePath: res.tempFilePath,
              success: (res) => {
                console.log("tempFilePath -=-=-", res)
                const {code, data: {url}} = JSON.parse(res.data);
                console.log("Upload success:", JSON.parse(res.data).data);
                if (code === 200) {
                  uni.navigateTo({
                    url: `/pages/photo_pay/photo_pay?type=1&image=` + encodeURIComponent(JSON.stringify(url))
                  })
                }
              },
              fail: (err) => {
                console.error('Upload failed:', err);
              }, complete: () => {
                uni.hideLoading()
              }
            });
          }
        })
      }, 2000)
    }
  }
})
</script>

<template>
  <view>
    <nav-bar :page-title="lang.page_name"/>
    <view class="padding-40">
      <view>
        <!-- radio 选择-->
        <view class="padding-20">
          <checkbox-group @change="onSelectedRadio">
            <view class="flex-center wrap">
              <label class="padding-20 text-28 gap-8 flex-center" v-for="(item, index) in idList" :key="index">
                <checkbox color="#1073FF" :value="index" :checked="item.isShow"/>
                <view>
                  {{
                    item.name === 'all' ? lang.id_list[item.name] : `${lang.id_list[item.name]} ${Math.ceil((index + 1) / 2)}`
                  }}
                </view>
              </label>
            </view>
          </checkbox-group>
        </view>
      </view>

      <view class="a4">
        <view class="flex-center wrap" style="justify-content: flex-start; gap: 8%">
          <view
              v-for="(item, index) in idList" v-if="item.isShow && item.icon !== ''" :key="index"
              :style="{'margin-left': item.ml, 'margin-right': item.mr, 'flex-direction': 'column'}"
          >
            <view class="id-card-box">
              <view v-if="item.file === ''" hover-class="hover" @click="showUploadImage(index)">
                <!-- 上传前-->
                <view class="column-center icon-card-box">
                  <view class="flex-column icon-card">
                    <u-icon size="34px" color="#1073FF" name="camera"/>
                  </view>
                </view>
                <image class="card-image" :src="item.icon"/>
              </view>

              <tempelate v-if="item.file !== '' && item.isShow">
                <view class="id-close-icon-box" @click="closeId(index)">
                  <u-icon size="26px" color="#0009" name="close-circle-fill"/>
                </view>
                <!-- 上传后-->
                <image class="card-image" :src="item.file" @click="onEditImage(index)"/>
              </tempelate>
            </view>
            <view class="title">{{ `${lang.id_list[item.name]} ${Math.ceil((index + 1) / 2)}` }}</view>
          </view>
        </view>
      </view>

      <!-- 打印-->
      <view style="margin-top: 30rpx;">
        <u-button
            shape="circle" @click="drawAndShareImage" size="large" color="#1073FF" :customStyle="{fontSize: '32rpx' }">
          {{ otherLang.print }}
        </u-button>
      </view>
    </view>

    <!-- 给服务器发送的和打印出的-->
    <view class="canvas">
      <canvas style="width: 3176px; height: 4492px;" canvas-id="multiIdCanvas" id="multiIdCanvas"/>
    </view>

    <view style="height: 200rpx;"/>

    <!-- 选择弹窗-->
    <upload-select-popup
        :show-popup="showUploadPopup" @choose-message="chooseMessage" @choose-image="chooseImage"
        @close-popup="showUploadPopup = false"/>
  </view>
</template>

<style scoped lang="scss">
.a4 {
  padding: 40rpx 40rpx;
  background: #fff;
  border-radius: 20rpx;
  height: 1100rpx;
  text-align: center;
}

.id-card-box {
  padding: 4rpx;
  width: 270rpx;
  height: 180rpx;
  position: relative;
  border-radius: 16rpx;
  border: 2rpx dashed #1073FF;
}


.id-card-box .card-image {
  width: 260rpx;
  height: 170rpx;
  border-radius: 16rpx;
}

.id-close-icon-box {
  position: absolute;
  top: 16rpx;
  right: 16rpx;
}


.a4 .title {
  text-align: center;
  padding: 10rpx;
}
</style>
